﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using Model;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using System.Text;
using System.Data;
using System.Configuration;

public partial class Spa_yuyue : WeiPage
{
    WeiXinRequestBO wbo = new WeiXinRequestBO();
    PersonInfoBO pbo = new PersonInfoBO();
    SubcribeBO sbo = new SubcribeBO();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Request.QueryString["code"] != null)
            {
                try
                {
                    string url = string.Format(@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + GetAppid() + "&secret=" + GetSecret() + "&code={0}&grant_type=authorization_code", Request.QueryString["code"].ToString());
                    string token = PostRequest(url);
                    if (token.Contains("7200"))
                    {
                        string[] b = token.Split('\"');
                        Session["FromUserName"] = b[13];
                        Session["ToUserName"] = "wx8ecea9aaa3d6162b";
                    }
                }
                catch (Exception)
                {

                }
            }

            for (int i = 0; i <= 6; i++)
            {
                ddlDate.Items.Add(new ListItem(DateTime.Now.AddDays(i).ToString("yyyy-MM-dd") + " " + GetWeek(DateTime.Now.AddDays(i)), DateTime.Now.AddDays(i).ToString("yyyy-MM-dd")));
            }

            if ((Request.QueryString["FromUserName"] != null || Session["FromUserName"] != null) && (Request.QueryString["ToUserName"] != null || Session["ToUserName"] != null))
            {
                string user = Request.QueryString["FromUserName"] == null ? Session["FromUserName"].ToString() : Request.QueryString["FromUserName"].ToString();
                string user2 = Request.QueryString["ToUserName"] == null ? Session["ToUserName"].ToString() : Request.QueryString["ToUserName"].ToString();

                Session["FromUserName"] = user;
                Session["ToUserName"] = user2;

                List<WeiXinRequest> list = wbo.GetModelList(string.Format(" Wxevent='location' AND FromUserName='{0}' ORDER BY id DESC ", user));
                if (list.Count == 0)
                {
//                    Response.Write(@"<script> var markerArr = [{ title: '佰草集汉方SPA', content: '佰草集汉方SPA', point: '121.467095|31.238878', isOpen: 0, icon: { w: 23, h: 25, l: 46, t: 21, x: 9, lb: 12} }
//		 ];
//        function createMap(){
//        var map = new BMap.Map('dituContent');
//        var point = new BMap.Point(121.488186,31.249162);
//        map.centerAndZoom(point,12);
//        window.map = map;
//    }</script>");
//                    Session["X"] = "121.467095";
//                    Session["Y"] = "31.238878";

                    List<Model> model = GetData(string.Format("{0}/resource/city/list.do", ConfigurationManager.AppSettings["yuyue"].ToString()));
                    if (model != null)
                    {
                        for (int i = 0; i < model.Count; i++)
                        {
                            ddlcity.Items.Add(new ListItem(model[i].name, model[i].value));                        
                            string md = string.Format(@"{0}/resource/city/{1}/subbranchlist.do",ConfigurationManager.AppSettings["yuyue"].ToString(),model[i].value);
                            GetData(md, ddlmd);
                            ddlcity_SelectedIndexChanged(null, null);

                        }

                    }
                }
                else
                {
//                    string mp = @"<script> var markerArr = [{ title: '你的位置', content: '你的位置', point: '{0}|{1}', isOpen: 0, icon: { w: 23, h: 25, l: 46, t: 21, x: 9, lb: 12} }
//		 ];
//function createMap(){
//        var map = new BMap.Map('dituContent');
//        var point = new BMap.Point({0},{1});
//        map.centerAndZoom(point,12);
//        window.map = map;
//    }</script>";
//                    mp = mp.Replace("{0}", Session["X"].ToString()).Replace("{1}", Session["Y"].ToString());
//                    Response.Write(mp);


                    Session["X"] = list[0].Location_X;
                    Session["Y"] = list[0].Location_Y;
                    WebClient client = new WebClient();
                    string url2 = "http://maps.google.com/maps/api/geocode/xml?latlng=" + list[0].Location_X + "," + list[0].Location_Y + "&language=zh-CN&sensor=false";
                    client.Encoding = Encoding.UTF8;
                    string responseTest = client.DownloadString(url2);

                    List<Model> model = GetData(string.Format("{0}/resource/city/list.do",ConfigurationManager.AppSettings["yuyue"].ToString()));
                    if (model != null)
                    {
                        for (int i = 0; i < model.Count; i++)
                        {
                            ddlcity.Items.Add(new ListItem(model[i].name, model[i].value));
                            if (responseTest.Contains(model[i].name))
                            {
                                ddlcity.SelectedValue = model[i].value;
                            }

                            string md = string.Format(@"{0}/resource/city/{1}/subbranchlist.do",ConfigurationManager.AppSettings["yuyue"].ToString(), model[i].value);
                            GetData(md, ddlmd);

                            ddlcity_SelectedIndexChanged(null, null);

                        }

                    }
                }                 
                    // Response.Redirect(string.Format("http://api.map.baidu.com/place/search?query=佰草集汉方SPA&location={0},{1}&radius=1000&region=上海&output=html&src=yourCompanyName|yourAppName", list[0].Location_X, list[0].Location_Y));
              

                PersonInfo p = pbo.GetModel(user);
                if (p != null)
                {
                    //GetCount();
                    Hname.Value = p.Name;
                    Hphone.Value = p.Phone;
                    Session["PersonNo"] = p.PersonNo;
                    tiao.HRef = "wodeyuyue.aspx?personNo=" + Session["PersonNo"];

                }
                else
                {
                    wx.Visible = true;
                    yy.Visible = false;
                    xm.Visible = false;
                    sj.Visible = false;
                    Label1.Text = "您还不是我们的会员，请点击上面的按钮成为会员";

                }
            }
           
            GetData(string .Format("{0}/resource/serviceitem/list.do",ConfigurationManager.AppSettings["yuyue"].ToString()), ddlxilie);
            //ListItem item = ddlmd.Items.FindByValue("8889");
            //if (item != null)
            //{
            //    ddlmd.Items.Remove(item);
            //}

        }
        
    }

    //private void GetCount()
    //{
    //    DataSet ds = sbo.YyCount(Session["FromUserName"].ToString());
    //    if (ds != null)
    //    {
    //        if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
    //        {

    //            yycount.InnerText = ds.Tables[0].Rows[0][0].ToString();
    //            //Response.Write(yycount.InnerText);
    //            if (Convert.ToInt32(ds.Tables[0].Rows[0][0]) > 0)
    //            {
    //                yycount.Visible = true;

    //            }
    //            else { yycount.Visible = false; }
    //        }

    //    }

    //}

    private void GetData(string url, DropDownList ddl)
    {
        string inter = url;
        string json = PostRequest(inter);
        Data data = JsonConvert.DeserializeObject<Data>(json);
        if (data.status == 0)
        {
            for (int i = 0; i < data.data.Count; i++)
            {
                ddl.Items.Add(new ListItem(data.data[i].name, data.data[i].value));
                ListItem item = ddl.Items.FindByValue("8889");
                if (item != null)
                {
                    ddl.Items.Remove(item);
                }
                ListItem item1 = ddl.Items.FindByValue("8888");
                if (item1 != null)
                {
                    ddl.Items.Remove(item1);
                }
                if (ddl == ddlcity)
                {
                    string md = string.Format(@"{0}/resource/city/{1}/subbranchlist.do",ConfigurationManager.AppSettings["yuyue"].ToString(),data.data[i].value);
                    GetData(md, ddlmd);

                }
            }
        }
        else
        {
            Response.Write("接口调用失败");
        }
    }


    private List<Model> GetData(string url)
    {
        string inter = url;
        string json = PostRequest(inter);
        Data data = JsonConvert.DeserializeObject<Data>(json);
        if (data.status == 0)
        {
            List<Model> list = new List<Model>();
            for (int i = 0; i < data.data.Count; i++)
            {

                Model model = data.data[i];

                list.Add(model);

            }
            return list;
        }
        else
        {

            Response.Write("接口调用失败");
            return null;
        }
    }

    public string GetWeek(DateTime d)
    {
        string[] Day = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
        string week = Day[Convert.ToInt32(d.DayOfWeek.ToString("d"))].ToString();
        return week;
    }

    class Data
    {
        public List<Model> data;
        public int status;
        public string message;
        public Data()
        {
            data = new List<Model>();
        }
    }

    class Model
    {
        public string code;
        public string name;
        public string value;
    }


    //提交预约
    protected void Button1_Click(object sender, EventArgs e)
    {
        string starttime = Convert.ToDateTime(ddlDate.SelectedValue + " " + ddlTime.SelectedValue + ":" + ddlMin.SelectedValue + ":00").ToString("yyyy-MM-dd HH:mm");
        string endtime = "";
        if (ddlxilie.SelectedValue == "-1")
        {
            AlertMessage("请选择所做项目");
            //endtime = Convert.ToDateTime(starttime).AddMinutes(90).ToString();
            //Label1.Text = "请选择所做项目";
        }
         if (ddlxilie.SelectedItem.ToString().Equals("脸部护理"))
        {
             endtime = Convert.ToDateTime(starttime).AddMinutes(120).ToString();
            //string endtime = Convert.ToDateTime(ddlDate.SelectedValue + " " + (int.Parse(ddlTime.SelectedValue) +2).ToString() + ":" + ddlMin.SelectedValue + ":00").ToString("yyyy-MM-dd HH:mm");
        }
        else if (ddlxilie.SelectedItem.ToString().Equals("全身护理"))
        {
            endtime = Convert.ToDateTime(starttime).AddMinutes(90).ToString();
            //string endtime = Convert.ToDateTime(ddlDate.SelectedValue + " " + (int.Parse(ddlTime.SelectedValue) + 1.5).ToString() + ":" + ddlMin.SelectedValue + ":00").ToString("yyyy-MM-dd HH:mm");
        }
        else if (ddlxilie.SelectedItem.ToString().Equals("混合护理"))
        {
             endtime = Convert.ToDateTime(starttime).AddMinutes(150).ToString();
            //string endtime = Convert.ToDateTime(ddlDate.SelectedValue + " " + (int.Parse(ddlTime.SelectedValue) + 3).ToString() + ":" + ddlMin.SelectedValue + ":00").ToString("yyyy-MM-dd HH:mm");
        }
        else if (ddlxilie.SelectedItem.ToString().Equals("足部护理"))
        {
             endtime = Convert.ToDateTime(starttime).AddMinutes(90).ToString();
            //string endtime = Convert.ToDateTime(ddlDate.SelectedValue + " " + (int.Parse(ddlTime.SelectedValue) + 1.5).ToString() + ":" + ddlMin.SelectedValue + ":00").ToString("yyyy-MM-dd HH:mm");
        }
      
        if (Convert.ToDateTime(starttime) < DateTime.Now)
        {
            AlertMessage("预约时间不能小于当前时间");
            //Label1.Text = "预约时间不能小于当前时间哦";
        }
      

        else
        {
            if (endtime == "")
            {
                AlertMessage("请选择所做项目");
            }
            else 
            { 
            if (Session["FromUserName"] != null)
            {
                string time = ddlTime.SelectedValue + ":" + ddlMin.SelectedValue;
                Subcribe sub = sbo.GetModel(Session["FromUserName"].ToString(), ddlDate.SelectedItem.ToString(), time);
                if (sub == null)
                {
                    //根据门店得到技师
                    string js = string.Format(@"{0}/resource/masseur/list.do/{1}",ConfigurationManager.AppSettings["yuyue"].ToString(), ddlmd.SelectedValue);
                    List<Model> list = GetData(js);
                    if (list != null)
                    {
                        //Response.Write(list.Count);
                        int i = 0;
                        while (i < list.Count)
                        {
                            if (Session["PersonNo"] != null)
                            {
                                int mdid = int.Parse(ddlmd.SelectedValue);
                                //会员卡号
                                //string hyka = "310109198811";
                                string hyka = Session["PersonNo"].ToString();
                                //1为会员 2为体验用户
                                //int hytype = 1;
                                string name = Hname.Value;
                                string phone = Hphone.Value;
                                string itemid = ddlxilie.SelectedValue;
                                //技师编号要填写
                                string jsid = list[i].value;
                                string djid = list[i].value;
                                string djname = list[i].name;
                                string d = @" {
                         ""SubBranchId"":{0:d},""MemberId"": ""{1}"", ""UserCard"":""{2}"",
                    ""UserCardType"":1,""UserFullName"":""{3}"", ""MobilePhone"": ""{4}"", ""Source"": 1,
                    ""ItemId"":""{5}"", ""OrderStartTime"":""{6}"", ""OrderEndTime"":
                    ""{7}"", ""MasseurId"":""{8}"",""BedName"": """"
                    , ""BookingUserId"": ""{8}"", ""BookingUserName"":""{9}"", ""BedId"":0}";
                                d = d.Replace("{0:d}", mdid.ToString()).Replace("{1}", "").Replace("{2}", hyka.Trim()).Replace("{3}", name)
                                    .Replace("{4}", phone).Replace("{5}", itemid).Replace("{6}", starttime).Replace("{7}", endtime)
                                    .Replace("{8}", jsid).Replace("{9}", djname);
                                var posturl =string.Format("{0}/booking/submit.do",ConfigurationManager.AppSettings["yuyue"].ToString());
                                //Response.Write(d);
                                var resMessage = HttpXmlPostRequest(posturl, d, Encoding.UTF8);
                                string[] b = resMessage.Split('\"');
                                //Response.Write(int.Parse(b[4].Substring(1, b[4].Length - 2)));
                                if (int.Parse(b[4].Substring(1, b[4].Length - 2)) == 0)
                                {
                                    Subcribe yuyue = new Subcribe();
                                    yuyue.City = ddlcity.SelectedItem.ToString();
                                    yuyue.StoreName = ddlmd.SelectedItem.ToString();
                                    if (ddlmd.SelectedItem.ToString().Contains("上海保定店"))
                                    {
                                        yuyue.Storetel = "021-65958808";
                                    }
                                    else if (ddlmd.SelectedItem.ToString().Contains("上海永银店"))
                                    {
                                        yuyue.Storetel = "021-63855050";
                                    }
                                    else if (ddlmd.SelectedItem.ToString().Contains("上海正大店"))
                                    {
                                        yuyue.Storetel = "021-60130389";
                                    }
                                    else if (ddlmd.SelectedItem.ToString().Contains("上海丽都店"))
                                    {
                                        yuyue.Storetel = "021-62171198";
                                    }
                                    else if (ddlmd.SelectedItem.ToString().Contains("上海世博店"))
                                    {
                                        yuyue.Storetel = "021-63855050";
                                    }
                                    else if (ddlmd.SelectedItem.ToString().Contains("上海船厂店"))
                                    {
                                        yuyue.Storetel = "021-60130389";
                                    }
                                    else if (ddlmd.SelectedItem.ToString().Contains("上海联洋店"))
                                    {
                                        yuyue.Storetel = "021-61650596";
                                    }
                                    else if (ddlmd.SelectedItem.ToString().Contains("上海淮海店"))
                                    {
                                        yuyue.Storetel = "021-63855050";
                                    }
                                    else if (ddlmd.SelectedItem.ToString().Contains("北京三里屯店"))
                                    {
                                        yuyue.Storetel = "010-64165179";
                                    }
                                    else if (ddlmd.SelectedItem.ToString().Contains("北京金融街店"))
                                    {
                                        yuyue.Storetel = "010-66290415";
                                    }
                                    else if (ddlmd.SelectedItem.ToString().Contains("北京凯德晶店"))
                                    {
                                        yuyue.Storetel = "010-68260331";
                                    }
                                 
                                    else if (ddlmd.SelectedItem.ToString().Contains("北京颐堤港店"))
                                    {
                                        yuyue.Storetel = "010-84260455";
                                    }
                                    else if (ddlmd.SelectedItem.ToString().Contains("北京金地店"))
                                    {
                                        yuyue.Storetel = "010-85713077";
                                    }
                                    else if (ddlmd.SelectedItem.ToString().Contains("北京远洋广场"))
                                    {
                                        yuyue.Storetel = "010-84445705";
                                    }
                                    else if (ddlmd.SelectedItem.ToString().Contains("苏州印象城店"))
                                    {
                                        yuyue.Storetel = "0512-68733826";
                                    }
                                    else if (ddlmd.SelectedItem.ToString().Contains("常州百盛店"))
                                    {
                                        yuyue.Storetel = "0519-1083836";
                                    }
                                    else if (ddlmd.SelectedItem.ToString().Contains("河南南阳店"))
                                    {
                                        yuyue.Storetel = "0377-61383838";
                                    }

                                    yuyue.YyDate = ddlDate.SelectedItem.ToString();
                                    yuyue.YyTime = ddlTime.SelectedValue + ":" + ddlMin.SelectedValue;
                                    yuyue.Name = Hname.Value;
                                    yuyue.FromUserName = Session["FromUserName"].ToString();
                                    yuyue.Phone = Hphone.Value;
                                    yuyue.Item = ddlxilie.SelectedItem.ToString();
                                    yuyue.Type = 0;
                                    yuyue.Result = "预约成功";
                                    yuyue.MasseurName = list[i].name;
                                    //会员卡号
                                    yuyue.PersonNo = hyka;
                                    yuyue.TjTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                    yuyue.BookingId = int.Parse(b[2].Substring(1, b[2].Length - 2));
                                    //Response.Write(resMessage + b[2]);
                                    int count = sbo.Add(yuyue);
                                    if (count > 0)
                                    {
                                        //Label1.Text = "预约成功";
                                        AlertMessage("预约成功,您的预计申请已经提交，稍后会有专人和您电话确认，敬请留意", Session["PersonNo"].ToString());
                                        //GetCount();
                                        //Button1.Enabled = false;
                                    }
                                    break;

                                }
                                else
                                {
                                    //if (b[7].Contains("该时间段已经被预约了,或者可以【预约排队】~"))
                                    //{
                                    //    i++;
                                    //    if (i >= list.Count)
                                    //    {
                                    //        AlertMessage("当前时间预约不了，换个时间段吧");
                                    //        //Label1.Text = "当前时间预约不了，换个时间段吧";
                                    //    }

                                    //}
                                    //else
                                    //{
                                    //    //Response.Write(resMessage);
                                    //    Label1.Text = b[7];
                                    //    break;
                                    //}

                                    i++;
                                    if (i >= list.Count)
                                    {
                                        //AlertMessage("当前时间预约不了，换个时间段吧");
                                        Label1.Text = "对不起，该时间段已经被他人预约，请调整预约时间或拨打客服中心电话4008200882";
                                    }
                                 

                                }

                            }

                        }

                    }
                }
                else
                {
                    if (sub.FromUserName.Equals(Session["FromUserName"].ToString()) && sub.YyDate.Equals(ddlDate.SelectedItem.ToString()) && sub.YyTime.Equals(time))
                    {
                        //AlertMessage("您已提交该时段的预约");
                        Label1.Text = "您已提交该时段的预约";
                        //GetCount();
                    }
                }
            }
        }

        }
    }

    protected void ddlTime_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlTime.SelectedValue == "11")
        {
            ddlMin.Items.Clear();
            ddlMin.Items.Add(new ListItem("30分", "30"));
            ddlMin.Items.Add(new ListItem("45分", "45"));
        }
        else if (ddlTime.SelectedValue == "22")
        {
            ddlMin.Items.Clear();
            ddlMin.Items.Add(new ListItem("00分", "00"));
            ddlMin.Items.Add(new ListItem("15分", "15"));
            ddlMin.Items.Add(new ListItem("30分", "30"));
        }
        else
        {
            ddlMin.Items.Clear();
            ddlMin.Items.Add(new ListItem("00分", "00"));
            ddlMin.Items.Add(new ListItem("15分", "15"));
            ddlMin.Items.Add(new ListItem("30分", "30"));
            ddlMin.Items.Add(new ListItem("45分", "45"));
        }
    }


    public static string HttpXmlPostRequest(string postUrl, string postXml, Encoding encoding)
    {
        if (string.IsNullOrEmpty(postUrl))
        {
            throw new ArgumentNullException("HttpXmlPost ArgumentNullException :  postUrl IsNullOrEmpty");
        }

        if (string.IsNullOrEmpty(postXml))
        {
            throw new ArgumentNullException("HttpXmlPost ArgumentNullException : postXml IsNullOrEmpty");
        }

        var request = (HttpWebRequest)WebRequest.Create(postUrl);
        byte[] byteArray = encoding.GetBytes(postXml);
        request.ContentLength = byteArray.Length;
        request.Method = "post";
        request.ContentType = "application/json;charset=utf-8";

        using (var requestStream = request.GetRequestStream())
        {
            requestStream.Write(byteArray, 0, byteArray.Length);
        }

        using (var responseStream = request.GetResponse().GetResponseStream())
        {
            return new StreamReader(responseStream, encoding).ReadToEnd();
        }
    }

    //protected void ddlcity_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    ddlmd.Items.Clear();
    //    ddlmd.Items.Add(new ListItem("请选择门店", ""));
    //    if (ddlcity.SelectedValue == "上海")
    //    {
    //        ddlmd.Items.Add(new ListItem("旗舰店", "121.467095,31.238878"));
    //        ddlmd.Items.Add(new ListItem("保定店", "121.515285,31.265157"));
    //        ddlmd.Items.Add(new ListItem("永银店", "121.487187,31.229545"));
    //        ddlmd.Items.Add(new ListItem("正大乐城店", "121.466104,31.192337"));
    //        ddlmd.Items.Add(new ListItem("联洋店", "121.56417,31.232502"));
    //    }
    //    else if (ddlcity.SelectedValue == "北京")
    //    {
    //        ddlmd.Items.Add(new ListItem("金融街", "116.368456,39.921006"));
    //        ddlmd.Items.Add(new ListItem("凯德晶品", "116.30395,39.91505"));
    //        ddlmd.Items.Add(new ListItem("颐堤港", "116.497383,39.975677"));
    //        ddlmd.Items.Add(new ListItem("远洋店", "116.440238,39.995855"));
    //    }
    //    else if (ddlcity.SelectedValue == "苏州")
    //    {
    //        ddlmd.Items.Add(new ListItem("印象城", "120.671008,31.321935"));
    //    }
    //    else if (ddlcity.SelectedValue == "常州")
    //    {
    //        ddlmd.Items.Add(new ListItem("正方京城", "119.962893,31.786805"));
    //    }
    //    else if (ddlcity.SelectedValue == "河南")
    //    {
    //        ddlmd.Items.Add(new ListItem("南阳店", "112.578252,32.995235"));
    //    }

    //}
    protected void ddlcity_SelectedIndexChanged(object sender, EventArgs e)
    {
        ddlmd.Items.Clear();
        string md = string.Format(@"{0}/resource/city/{1}/subbranchlist.do",ConfigurationManager.AppSettings["yuyue"].ToString(), ddlcity.SelectedValue);
        GetData(md, ddlmd);

    }


    public void AlertMessage(string message,string personno)
    {
        if (message.Equals("预约成功,您的预计申请已经提交，稍后会有专人和您电话确认，敬请留意"))
        {

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alertCloseReload", "<script>alert(\"" + message + "\");window.location.href='wodeyuyue.aspx?personNo=" + personno + "';</script>");

        }
        else
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alertCloseReload", "<script>alert(\"" + message + "\");</script>");
        }
    }
}